<template>
  <!--- 操作点检详情 -->
  <view v-if="formSubmit.contentList.length > 0">
    <uni-forms ref="form" :rules="rules" labelPosition="top" labelWidth="120px">
      <view class="grid-body mt-30" v-for="(item, index) in formSubmit.contentList" :key="index">
        <view class="check grid-common">
          <view class="title flex">
            <image class="icon-style" :src="getStatus(item)[0]" mode="aspectFill"></image>
            {{ getStatus(item)[1] }}
          </view>
          <view class="flex text"
            >点检部位：
            <text>{{ item.part || '--' }}</text>
          </view>
          <view class="flex text"
            >点检方式：
            <text>{{ item.modeLabel || '--' }}</text>
          </view>
          <view class="flex text"
            >关联检测点位：
            <text>{{ item.devicePointLabel || '--' }}</text>
          </view>
          <view class="flex">
            <view class="text">点检内容：</view>
            <text class="flex-1 text">{{ item.content || '--' }}</text>
          </view>
          <view class="flex">
            <view class="text">标准描述：</view>
            <text class="flex-1 text">{{ item.standard || '--' }}</text>
          </view>
          <view class="flex">
            <view class="text">上限：</view>
            <text class="flex-1 text">{{ item.upperLimit || '--' }}</text>
          </view>
          <view class="flex">
            <view class="text">下限：</view>
            <text class="flex-1 text">{{ item.lowerLimit || '--' }}</text>
          </view>
          <view class="flex">
            <view class="text">单位：</view>
            <text class="flex-1 text">{{ item.unit || '--' }}</text>
          </view>
          <view class="flex">
            <view class="text">安全措施：</view>
            <text class="flex-1 text">{{ item.securityMeasure || '--' }}</text>
          </view>
          <view class="flex text" v-if="item.taskStatus == '2' || item.taskStatus == '4' || readOnly"
            >测点值：
            <text>{{ item.pointValue || '--' }}</text>
          </view>
          <view class="flex text" v-if="item.taskStatus == '2' || item.taskStatus == '4' || readOnly"
            >巡检结果：
            <text>{{ item.resultStatusLabel }}</text>
          </view>
          <uni-forms-item
            v-if="(item.taskStatus == '1' || item.taskStatus == '3') && !readOnly"
            name="pointValue"
            class="mt-20"
            label="测点值:"
          >
            <view class="flex">
              <textarea
                :class="{
                  'text-area': true,
                  'error-text-Area': getColor(item)
                }"
                v-model="item.pointValue"
                :style="{
                  width: item.mode == 2 || item.mode == 3 ? 'calc(100% - 200rpx)' : ''
                }"
                maxlength="50"
                @focus="handleFocus()"
              />
            </view>
          </uni-forms-item>
          <view class="flex bor-top" v-if="(item.taskStatus == '1' || item.taskStatus == '3') && !readOnly">
            <button class="u-button small" @click="handleClickStage(item, '1')">正常</button>
            <button class="u-button u-button-danger small" @click="handleClickStage(item, '2')">上报隐患</button>
            <button class="u-button u-button-orange small" @click="handleClickStage(item, '3')">上报缺陷</button>
          </view>
        </view>
      </view>
    </uni-forms>
  </view>
  <view v-else>
    <empty></empty>
  </view>
</template>

<script>
import Empty from '@/components/cu-empty/index.vue'
import { getDeviceBySubTaskItemId, executeItemDeviceInfoTask } from '@/api/equipment/spotCheck'
import { managerSourceEnum } from '@/utils/constant'
// 获取 module
export default {
  name: 'pointCheck',
  components: {
    Empty
  },
  data() {
    return {
      samTemp: false,
      formSubmit: {
        id: '',
        contentList: []
      },
      readOnly: false,
      deviceId: '',
      areaId: '',
      subTaskPathId: '',
      deviceName: '',
      rules: {
        pointValue: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        }
      }
    }
  },
  onLoad({ subTaskPathId, deviceId, deviceName, areaName, readOnly, areaId }) {
    this.subTaskPathId = subTaskPathId
    this.deviceId = deviceId
    this.deviceName = deviceName
    this.areaName = areaName
    this.areaId = areaId
    this.readOnly = readOnly && readOnly !== 'undefined' ? readOnly : false
    this.setTitle(deviceName)
    this.getDetail()
  },
  onPullDownRefresh() {
    this.getDetail()
  },
  beforeDestroy() {

  },
  methods: {
    getColor(item) {
      if (item.mode == 2 || item.mode == 3) {
        if (item.lowerLimit && item.upperLimit && item.pointValue && Number(item.pointValue, 10) !== NaN) {
          if (
            Number(item.pointValue) >= Number(item.lowerLimit) &&
            Number(item.pointValue) <= Number(item.upperLimit)
          ) {
          } else {
            return true
          }
        }
      }
      return false
    },
    setTitle(title) {
      uni.setNavigationBarTitle({
        title: title
      })
    },
    async getDetail() {
      let { data } = await getDeviceBySubTaskItemId(this.subTaskPathId)
      this.formSubmit.contentList = data
    },
    getStatus(item) {
      switch (item.taskStatus) {
        case '2':
          return ['/static/images/inspection-1.png', '已巡检']

        case '3':
          return ['/static/images/inspection-3.png', '逾期未巡检']
        case '4':
          return ['/static/images/inspection-3.png', '逾期完成']

        case '1':
          return ['/static/images/inspection-2.png', '未巡检']
        default:
          return ['/static/images/inspection-2.png', '未巡检']
      }
    },
    getStatusLabel(status) {
      switch (status) {
        case '1':
          return '正常'

        case '2':
          return '存在异常'
        case '3':
          return '存在异常'
      }
    },

    /** * 初始化蓝牙成功 * @param {*} options  */

    openBluetoothAdapter() {
      const error = {
        10000: '未初始化蓝牙适配器',
        10001: '当前蓝牙适配器不可用，请检查蓝牙是否开启',
        10002: '没有找到指定设备',
        10003: '蓝牙连接失败'
      }
      return new Promise((resolve, reject) => {
        uni.openBluetoothAdapter({
          success: (e) => {
            console.log('初始化蓝牙成功')
            resolve()
          },
          fail: (err) => {
            reject({
              code: err.code,
              msg: error[err.code]
            })
            if (err.code === 10001) {
              uni.showModal({
                title: '提示',
                content: '请打开蓝牙功能',
                success(res) {}
              })
            } else {
              showToast(error[err.code])
            }
          }
        })
      })
    },
    /**检查是否打开GPS功能（android）**/
    checkOpenGPSServiceByAndroid(options) {
      let system = uni.getSystemInfoSync()
      // 获取系统信息
      return new Promise((resolve, reject) => {
        if (system.platform === 'android') {
          // 判断平台
          var context = plus.android.importClass('android.content.Context')
          var locationManager = plus.android.importClass('android.location.LocationManager')
          var main = plus.android.runtimeMainActivity()
          var mainSvr = main.getSystemService(context.LOCATION_SERVICE)
          if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
            uni.showModal({
              title: '提示',
              content: '请打开定位服务功能',
              success(res) {}
            })
            reject({
              msg: '请在设置中开启系统位置服务'
            })
          } else {
            resolve()
          }
        }
      })
    },
    handleClickMode(item) {

    },
    execute(item) {

    },
    handleFocus() {

    },
    stopSampleTemp() {

    },
    sampleTemp(item) {

    },
    sampleVib(item) {
      
    },
    // waveData(arrayList, freq) {
    //   let UpperLimitingFreq = freq; //上限频率
    //   let data_sampling = int(freq * 2.56); ////采样频率
    //   let measureDataAcc = new Array(arrayList.length);//0加速度数据存储
    //   let sum = 0.0;
    //   if (measureDataAcc != null && measureDataAcc.length > 0) {

    //   }
    // },
    handleClickStage(item, type) {
      if (!item.pointValue) {
        this.$modal.msgError('请输入测点值')
        return
      }
      if (type === '1') {
        //直接保存
        item.resultStatus = '1'
        this.saveForm(item)
      } else if (type === '2') {
        item.resultStatus = '2'
        uni.navigateTo({
          url: `/pages/work/hiddenDangerReport/index?reportType=2&managerSource=${managerSourceEnum.DEVICEINSPECT}&areaId=${this.areaId}`,
          events: {
            'callback:success': (data) => {
              this.saveForm(item)
            }
          }
        })
      } else {
        item.resultStatus = '3'
        uni.navigateTo({
          url: `/pages/work/intelligentPatrolInspection/spotCheck/reportDefects?location=${this.areaName}&deviceId=${this.deviceId}&deviceName=${this.deviceName}`,
          events: {
            'callback:success': (data) => {
              this.saveForm(item)
            }
          }
        })
      }
    },
    saveForm(data) {
      executeItemDeviceInfoTask(data).then(() => {
        this.$modal.msgSuccess('执行成功')
        //查询
        this.getDetail()
      })
    },
    navigateBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.check {
  position: relative;

  .title {
    font-size: 34rpx;
    font-weight: 700;
  }

  .icon-style {
    width: 52rpx;
    height: 52rpx;
    margin-right: 20rpx;
  }

  .text {
    color: #999;
  }

  .flex-text {
    padding-top: 24rpx;
    display: flex;
    color: #999;

    text {
      color: #333;
      display: inline-block;
    }
  }

  .bor-top {
    padding-top: 20rpx;
    border-top: 1px solid #d5d7e3;
  }
}

.text-area {
  background: #f5f5f5;
  color: #333;
  border-radius: 10rpx;
  width: 100%;
  padding: 20rpx;
  height: 220rpx;
  font-size: 30rpx;
}

:deep(.uni-textarea-textarea) {
  color: red;
}

:deep(.uni-forms-item__label) {
  color: #999;
}
</style>
